'use strict';
var mysql = require("mysql");
var moment = require("moment");
var promisify = require('./promisecover').promisify;
var _ = require('lodash');
var pool = null;
var log4js = require('log4js');
var log = log4js.getLogger("dbs");

function nop(a, b, c, d, e, f, g) {

}

function query(sql, callback) {
    pool.query(sql, function (err, vals, fields) {
        if (err) {
            callback(err, null, null);
        } else {
            callback(err, vals, fields);
        }
    });
}


function queryAsync(sql, callback) {
    var query = promisify(pool.query, pool)
    return query;
}



function ArgsQuery(sql, argsArray, callback) {
    pool.query(sql, argsArray, function (err, vals, fields) {
        if (err) {
            console.log(err);
            callback(err, null, null);
        } else {
            callback(err, vals, fields);
        }
    });
}


function transactionQuery(queryFun, sql) {
    return queryFun(sql);
}

exports.init = function (config) {
    pool = mysql.createPool({
        host: config.HOST,
        user: config.USER,
        password: config.PSWD,
        database: config.DB,
        port: config.PORT,
    });
    // 创建连接池连接
    pool.on('connection', function (connection) {
        log.info('MYSQL数据库连接已分配')
        connection.on('error', function (err) {
            log.warn('MYSQL数据库操作错误: %s', err);
        });
        connection.on('end', function (err) {
            log.info('MYSQL数据库连接结束: %s', err);
        });
    });
};

/**
 * 创建事务
 */
exports.beginTransaction = function (queryCb) {
    return new Promise(function (resolve, reject) {
        pool.getConnection(function (err, conn) {
            if (err) {
                conn.release();
                reject(err);
            }
            conn.beginTransaction(function (err) {
                if (err) {
                    conn.release();
                    reject(err);
                }
                var query = promisify(conn.query, conn);
                queryCb(query).then(function (value) {
                    conn.commit(function () {
                        conn.release();
                        resolve(value);
                    });
                }).catch(function (queryErr) {
                    conn.rollback(function () {
                        conn.release();
                        reject(queryErr);
                    });
                });
            });
        });
    });
};


exports.is_account_exist = function (account, callback) {
    callback = callback == null ? nop : callback;
    if (account == null) {
        callback(false);
        return;
    }

    var sql = 'SELECT * FROM t_accounts WHERE account = "' + account + '"';
    query(sql, function (err, rows, fields) {
        if (err) {
            callback(false);
            console.log("err: is_account_exist fail! error message == " + err);
        }
        else {
            if (rows.length > 0) {
                callback(true);
            }
            else {
                callback(false);
            }
        }
    });
};

exports.create_account = function (account, password, callback) {
    callback = callback == null ? nop : callback;
    if (account == null || password == null) {
        callback(false);
        return;
    }

    var psw = crypto.md5(password);
    var sql = 'INSERT INTO t_accounts(account,password) VALUES("' + account + '","' + psw + '")';
    query(sql, function (err, rows, fields) {
        if (err) {
            if (err.code == 'ER_DUP_ENTRY') {
                callback(false);
                console.log("err: create_account fail error message == " + err);
                return;
            }
            callback(false);
            console.log("err: create_account fail error message == " + err);
        }
        else {
            callback(true);
        }
    });
};

exports.get_account_info = function (account, password, callback) {
    callback = callback == null ? nop : callback;
    if (account == null) {
        callback(null);
        return;
    }

    var sql = 'SELECT * FROM t_accounts WHERE account = "' + account + '"';
    query(sql, function (err, rows, fields) {
        if (err) {
            callback(null);
            console.log("err: get_account_info fail error message == " + err);
            return;
        }

        if (rows.length == 0) {
            callback(null);
            console.log("err: get_account_info fail no content ");
            return;
        }

        if (password != null) {
            var psw = crypto.md5(password);
            if (rows[0].password == psw) {
                callback(null);
                return;
            }
        }

        callback(rows[0]);
    });
};

exports.is_user_exist = function (account, callback) {
    callback = callback == null ? nop : callback;
    if (account == null) {
        callback(0, false);
        return;
    }

    var sql = 'SELECT userid FROM t_users WHERE account = "' + account + '"';
    query(sql, function (err, rows, fields) {
        if (err) {
            callback(0, false);
            console.log("err: get_account_info fail error message == " + err);
            return;
        }

        if (rows.length == 0) {
            callback(0, false);
            return;
        }

        callback(rows[0].userid, true);
    });
}

exports.get_user_data = function (account, callback) {
    callback = callback == null ? nop : callback;
    if (account == null) {
        callback(null);
        return;
    }

    var sql = 'SELECT userid,account,name,lv,exp,coins,gems,sex,roomid,headimg,regIp FROM t_users WHERE account = "' + account + '"';
    console.log(sql);
    query(sql, function (err, rows, fields) {
        if (err) {
            callback(null);
            console.log("err: get_user_data fail error message == " + err);
            return;
        }

        if (rows.length == 0) {
            callback(null);
            return;
        }

        callback(rows[0]);
    });
};

exports.get_vip_user_data = function (name, callback) {
    callback = callback == null ? nop : callback;
    var sql = 'SELECT userid,account,name,lv,exp,coins,gems,sex,roomid,headimg FROM t_users WHERE lv = 999 and name like "{0}" or name like "{1}"';
    sql = sql.format(name[0], name[1]);
    console.log(sql);
    query(sql, function (err, rows, fields) {
        if (err) {
            callback(null);
            console.log("err: get_user_data fail error message == " + err);
            return;
        }

        if (rows.length == 0) {
            callback(null);
            return;
        }

        callback(rows);
    });
};

exports.get_all_user_info = function (callback) {
    callback = callback == null ? nop : callback;
    var sql = 'SELECT * FROM t_users';
    //console.log(sql);
    query(sql, function (err, rows, fields) {
        if (err) {
            callback(null, null);
            console.log("err: get_all_user_info fail error message == " + err);
            return;
        }

        if (rows.length == 0) {
            callback(null, null);
            return;
        }

        // var user_setting = {};
        // var user_account = {};
        // for (var i = 0; i < rows.length; ++i) {
        //     var userinfo = {
        //         userid: rows[i].userid,
        //         account: rows[i].account,
        //         name: rows[i].name,
        //         sex: rows[i].sex,
        //         headimg: rows[i].headimg,
        //         lv: rows[i].lv,
        //         exp: rows[i].exp,
        //         coins: rows[i].coins,
        //         gems: rows[i].gems,
        //         roomid: rows[i].roomid,
        //         online: rows[i].online,
        //         create_time: rows[i].create_time
        //     };
        //     user_setting[rows[i].userid] = userinfo;
        //     user_account[rows[i].account] = rows[i].userid;
        // }
        callback(rows);
    });
}

exports.get_gems = function (account, callback) {
    callback = callback == null ? nop : callback;
    if (account == null) {
        callback(null);
        return;
    }

    var sql = 'SELECT gems FROM t_users WHERE account = "' + account + '"';
    query(sql, function (err, rows, fields) {
        if (err) {
            callback(null);
            console.log("err: get_gems fail error message == " + err);
            return;
        }

        if (rows.length == 0) {
            callback(null);
            return;
        }

        callback(rows[0].gems);
    });
};

exports.get_gems_and_coins = function (account, callback) {
    callback = callback == null ? nop : callback;
    if (account == null) {
        callback(null);
        return;
    }

    var sql = 'SELECT gems,coins FROM t_users WHERE account = "' + account + '"';
    query(sql, function (err, rows, fields) {
        if (err) {
            callback(null);
            console.log("err: get_gems fail error message == " + err);
            return;
        }

        if (rows.length == 0) {
            callback(null);
            return;
        }

        callback(rows[0]);
    });
};

exports.get_user_history = function (userId, callback) {
    callback = callback == null ? nop : callback;
    if (userId == null) {
        callback(null);
        return;
    }
    var sql = "SELECT room_id, COUNT(*) as count FROM t_each_round_history WHERE userid1 = {0} or userid2 = {0} or userid3 = {0} or userid4 = {0} GROUP BY room_id ORDER BY begin_time DESC LIMIT 20";
    sql = sql.format(userId);
    query(sql, function (err, rows) {
        if (err) {
            callback(null);
            console.log("err: get_user_history fail error message == " + err);
            return;
        }
        if (rows.length === 0) {
            callback(null);
            return;
        }
        exports.get_rooms_history(rows, function (ret) {
            if (ret && Object.keys(ret).length > 0) {
                Object.keys(ret).forEach(function (listKey) {
                    var list = ret[listKey];
                    list.seats[0] = list.seats[0].filter(function (seat) { return seat != null; });
                    var sumUserInfo = _.cloneDeep(list.seats[0]);
                    for (var i = 1; i < list.seats.length; i++) {
                        list.seats[i] = list.seats[i].filter(function (seat) { return seat != null; });
                        list.seats[i].forEach(function (value, index) {
                            sumUserInfo[index].score += value.score;
                        });
                    }
                    list.seats = sumUserInfo;
                });
            }
            callback(ret);
        });
    });
};

exports.get_rooms_history = function (roomIds, callback) {
    callback = callback == null ? nop : callback;
    if (roomIds.length === 0) {
        callback(null);
        return;
    }
    var sql = "SELECT room_id, round_no, history, UNIX_TIMESTAMP(begin_time) as begin_time FROM t_each_round_history WHERE";
    var where = "";
    var orderBy = " ORDER BY begin_time DESC";
    roomIds.forEach(function (roomId, index) {
        if (index === roomIds.length - 1) {
            where += " room_id = " + roomId.room_id;
        } else {
            where += " room_id = " + roomId.room_id + " OR";
        }
    });
    sql += where + orderBy;
    console.log(sql);
    query(sql, function (err, rows) {
        if (err) {
            callback(null);
            console.log("err: get_user_history fail error message == " + err);
            return;
        }
        if (rows.length === 0) {
            callback(null);
            return;
        }
        var data = {};

        for (var i = 0; i < roomIds.length; i++) {
            if (!roomIds.count) {
                roomIds.count = rows.length;
            }
            data[i] = {};
            var count = 0;
            for (var j = 0; j < rows.length; ++j) {
                var history = rows[j].history;
                if (history == null || history === "") {
                    continue;
                }
                else {
                    if (rows[j].room_id == roomIds[i].room_id) {
                        count++;
                        if (!data[i].seats) {
                            data[i].begin_time = rows[j].begin_time;
                            data[i].room_id = rows[j].room_id;
                            data[i].seats = [];
                        }
                        data[i].seats.unshift(JSON.parse(history).seats);
                        if (count === roomIds.count) {
                            break;
                        }
                    }
                }
            }
        }
        callback(data);
    });
};

exports.store_eachround_history = function (game, roomInfo, callback) {
    //庄家
    callback = callback == null ? nop : callback;
    var seats = roomInfo.seats;
    var history = {
        uuid: roomInfo.uuid,
        id: roomInfo.id,
        time: roomInfo.createTime,
        seats: new Array(seats.length)
    };

    var sql = "insert into t_each_round_history (room_uuid,room_id,banker_index,history,round_no";
    var userVal = "";
    for (var i = 0; i < seats.length; ++i) {
        var rs = seats[i];
        var hs = history.seats[i] = {};
        hs.userid = rs.userId;
        hs.name = rs.name;
        hs.score = 0;
        sql += (",userid" + (i + 1));
        userVal += ("," + rs.userId);
    }

    //构造语句
    history = JSON.stringify(history);
    sql += ") values ('{0}','{1}',{2},'{3}',{4} ";
    sql = sql.format(roomInfo.uuid, roomInfo.id, roomInfo.nextButton, history, roomInfo.numOfGames);
    sql += (userVal + ")");
    console.log(sql);
    query(sql, function (err, rows, fields) {
        if (err) {
            callback(false);
            console.log("err: store_eachround_game fail error message == " + err);
        }
        else {
            callback(true);
        }
    });
}

exports.store_shisanshui_eachround_history = function (game, roomInfo, callback) {
    //庄家
    callback = callback == null ? nop : callback;
    var seats = roomInfo.seats;
    var history = {
        uuid: roomInfo.uuid,
        id: roomInfo.id,
        time: roomInfo.createTime,
        seats: new Array(seats.length)
    };

    var sql = "insert into t_shisanshui_each_round_history (room_uuid,room_id,banker_mode,history,round_no,seat_len";
    var userVal = "";
    for (var i = 0; i < seats.length; ++i) {
        var rs = seats[i];
        var hs = history.seats[i] = {};
        hs.userid = rs.userId;
        hs.name = rs.name;
        hs.score = 0;
        sql += (",userid" + i);
        sql += (",score" + i);
        userVal += ("," + rs.userId + "," + rs.score);
    }

    //构造语句
    history = JSON.stringify(history);
    sql += ") values ('{0}','{1}',{2},'{3}',{4}, {5}";
    sql = sql.format(roomInfo.uuid, roomInfo.id, roomInfo.conf.zhuangMode, history, roomInfo.numOfGames, seats.length);
    sql += (userVal + ")");
    console.log(sql);
    query(sql, function (err, rows, fields) {
        if (err) {
            callback(false);
            console.log("err: store_shisanshui_eachround_history fail error message == " + err);
        }
        else {
            callback(true);
        }
    });
}

exports.store_eachround_result = function (game, roomInfo, storeAllRes, callback) {
    //庄家
    callback = callback == null ? nop : callback;

    var seats = roomInfo.seats;
    var result = {
        id: roomInfo.id,
        seats: new Array(seats.length)
    };
    for (var i = 0; i < seats.length; ++i) {
        var rs = seats[i];
        var hs = result.seats[i] = {};
        hs.userid = rs.userId;
        hs.name = rs.name;
        hs.res = storeAllRes.res[i];
    }

    //构造语句
    result = JSON.stringify(result);
    var sql = "insert into t_each_round_users (room_id,round_no,users,scores,winner,fangPaoUser,results) values ('{0}',{1},'{2}','{3}','{4}',{5},'{6}')";
    sql = sql.format(roomInfo.id, roomInfo.numOfGames, storeAllRes.userList, storeAllRes.scoreList, storeAllRes.winner, storeAllRes.fangpaoUser, result);
    console.log(sql);
    query(sql, function (err, rows, fields) {
        if (err) {
            callback(false);
            console.log("err: store_eachround_game fail error message == " + err);
        }
        else {
            callback(true);
        }
    });
}

exports.update_each_round_history = function (roomInfo, dbresult, callback) {
    //构造历史数据
    callback = callback == null ? nop : callback;
    var seats = roomInfo.seats;
    var history = {
        uuid: roomInfo.uuid,
        id: roomInfo.id,
        time: roomInfo.createTime,
        seats: new Array(seats.length)
    };
    for (var i = 0; i < seats.length; ++i) {
        var rs = seats[i];
        var hs = history.seats[i] = {};
        hs.userid = rs.userId;
        hs.name = rs.name;
        hs.score = dbresult[i];
    }

    //构造语句
    history = JSON.stringify(history);
    var sql = 'update t_each_round_history set end_time = now(), history = \'' + history + '\'  WHERE room_id = ' + roomInfo.id + ' and round_no = ' + roomInfo.numOfGames;
    console.log(sql);
    query(sql, function (err, rows, fields) {
        if (err) {
            callback(false);
            console.log("err: update_each_round_history fail error message == " + err);
        }
        else {
            callback(true);
        }
    });
}

exports.update_shisanshui_each_round_history = function (roomInfo, callback) {
    //构造历史数据
    callback = callback == null ? nop : callback;
    var seats = roomInfo.seats;
    var history = {
        uuid: roomInfo.uuid,
        id: roomInfo.id,
        time: roomInfo.createTime,
        seats: new Array(seats.length)
    };

    var userVal = "";
    var scoreVal = "";
    for (var i = 0; i < seats.length; ++i) {
        var rs = seats[i];
        var hs = history.seats[i] = {};
        hs.userid = rs.userId;
        hs.name = rs.name;
        hs.score = rs.score;
        userVal = userVal + (", userid" + i) + " = " + rs.userId;
        scoreVal = scoreVal + (", score" + i) + " = " + rs.score;
    }

    //构造语句
    history = JSON.stringify(history);
    var sql = 'update t_shisanshui_each_round_history set end_time = now() ' + userVal + scoreVal + ', history = \''
        + history + '\'  WHERE room_id = ' + roomInfo.id + ' and round_no = ' + roomInfo.numOfGames;
    console.log(sql);
    query(sql, function (err, rows, fields) {
        if (err) {
            callback(false);
            console.log("err: update_shisanshui_each_round_history fail error message == " + err);
        }
        else {
            callback(true);
        }
    });
}

exports.get_games_of_room = function (room_uuid, callback) {
    callback = callback == null ? nop : callback;
    if (room_uuid == null) {
        callback(null);
        return;
    }

    var sql = 'SELECT game_index,create_time,result FROM t_games_archive WHERE room_uuid = "' + room_uuid + '"';
    //console.log(sql);
    query(sql, function (err, rows, fields) {
        if (err) {
            callback(null);
            console.log("err: get_games_of_room fail error message == " + err);
            return;
        }

        if (rows.length == 0) {
            callback(null);
            return;
        }

        callback(rows);
    });
};

exports.get_detail_of_game = function (room_uuid, index, callback) {
    callback = callback == null ? nop : callback;
    if (room_uuid == null || index == null) {
        callback(null);
        return;
    }
    var sql = 'SELECT base_info,action_records FROM t_games_archive WHERE room_uuid = "' + room_uuid + '" AND game_index = ' + index;
    console.log(sql);
    query(sql, function (err, rows, fields) {
        if (err) {
            callback(null);
            console.log("err: get_detail_of_game fail error message == " + err);
            return;
        }
        if (rows.length == 0) {
            callback(null);
            return;
        }
        callback(rows[0]);
    });
}

exports.create_user = function (userid, account, name, coins, gems, sex, headimg, ip, callback) {
    callback = callback == null ? nop : callback;
    if (account == null || name == null || coins == null || gems == null) {
        callback(0, false);
        return;
    }
    if (headimg == null) {
        headimg = 'null';
    }
    var sql = 'INSERT INTO t_users(userid,account,name,coins,gems,sex,headimg,regIp) VALUES ({0},"{1}","{2}",{3},{4},{5},"{6}","{7}")';
    sql = sql.format(userid, account, name, coins, gems, sex, headimg, ip);
    console.log(sql);
    query(sql, function (err, rows, fields) {
        if (err) {
            callback(0, false);
            console.log("err: create_user fail error message == " + err);
            return;
        }
        callback(userid, true);
    });
};

exports.get_max_userid = function (callback) {
    callback = callback == null ? nop : callback;
    var sql = 'select MAX(userid)"userid" from t_users';
    console.log(sql);
    query(sql, function (err, rows, fields) {
        if (err) {
            callback(false);
            console.log("err: get_max_userid fail error message == " + err);
            return;
        }
        callback(rows[0]);
    });
};

exports.is_userid_exist = function (userid, callback) {
    callback = callback == null ? nop : callback;
    var sql = 'select count(1) as count from t_users where userid = ' + userid;
    console.log(sql);
    query(sql, function (err, rows, fields) {
        if (err) {
            callback(false);
            console.log("err: is_userid_exist fail error message == " + err);
            return;
        }
        callback(rows[0].count);
    });
};

exports.update_user_info = function (account, name, headimg, sex, callback) {
    callback = callback == null ? nop : callback;
    if (account == null) {
        callback(false);
        return;
    }

    if (headimg) {
        headimg = '"' + headimg + '"';
    }
    else {
        headimg = 'null';
    }

    var sql = 'UPDATE t_users SET name="{0}",headimg={1},sex={2} WHERE account="{3}"';
    sql = sql.format(name, headimg, sex, account);
    console.log(sql);
    query(sql, function (err, rows, fields) {
        if (err) {
            callback(false);
            console.log("err: update_user_info fail error message == " + err);
            return;
        }
        if (rows.length <= 0) {
            callback(false);
            console.log("err: update_user_info fail error message == " + err);
            return;
        }
        callback(true);
    });
};

exports.get_user_base_info = function (userid, callback) {
    callback = callback == null ? nop : callback;
    if (userid == null) {
        callback(null);
        return;
    }
    var sql = 'SELECT name,sex,headimg FROM t_users WHERE userid={0}';
    sql = sql.format(userid);
    //console.log(sql);
    query(sql, function (err, rows, fields) {
        if (err) {
            console.log("err: get_user_base_info fail error message == " + err);
            callback(null);
            return;
        }
        if (rows.length <= 0) {
            console.log("err: get_user_base_info fail error message == " + err);
            callback(null);
            return;
        }
        callback(rows[0]);
    });
};

exports.is_room_exist = function (roomId, callback) {
    callback = callback == null ? nop : callback;
    var sql = 'SELECT * FROM t_rooms WHERE id = "' + roomId + '"';
    query(sql, function (err, rows, fields) {
        if (err) {
            callback(false);
            console.log("err: is_room_exist fail error message == " + err);
        }
        else {
            callback(rows.length > 0);
        }
    });
};

exports.cost_gems = function (userid, cost, callback) {
    callback = callback == null ? nop : callback;
    var sql = 'UPDATE t_users SET gems = gems -' + cost + ' WHERE userid = ' + userid;
    console.log(sql);
    query(sql, function (err, rows, fields) {
        if (err) {
            callback(false);
            console.log("err: cost_gems fail error message == " + err);
        }
        else {
            callback(rows.length > 0);
        }
    });
};

exports.set_room_id_of_user = function (userId, roomId, callback) {
    callback = callback == null ? nop : callback;
    if (roomId != null) {
        roomId = '"' + roomId + '"';
    }
    var sql = 'UPDATE t_users SET roomid = ' + roomId + ' WHERE userid = ' + userId;
    console.log(sql);
    query(sql, function (err, rows, fields) {
        if (err) {
            callback(false);
            console.log("err: set_room_id_of_user fail error message == " + err);
        }
        else {
            callback(rows.length > 0);
        }
    });
};

exports.get_room_id_of_user = function (userId, callback) {
    callback = callback == null ? nop : callback;
    var sql = 'SELECT roomid FROM t_users WHERE userid = "' + userId + '"';
    query(sql, function (err, rows, fields) {
        if (err) {
            callback(null);
            console.log("err: get_room_id_of_user fail error message == " + err);
        }
        else {
            if (rows.length > 0) {
                callback(rows[0].roomid);
            }
            else {
                callback(null);
            }
        }
    });
};

exports.get_user_isConfig_pai = function (userId, callback) {
    callback = callback == null ? nop : callback;
    var sql = 'SELECT isConfigPai FROM t_users WHERE userid = "' + userId + '"';
    query(sql, function (err, rows, fields) {
        if (err) {
            callback(null);
            console.log("err: get_room_id_of_user fail error message == " + err);
        }
        else {
            if (rows.length > 0) {
                callback(rows[0].isConfigPai);
            }
            else {
                callback(null);
            }
        }
    });
};

exports.create_room = function (roomId, conf, ip, port, maxGames, cost, create_time, seat_num, callback) {
    callback = callback == null ? nop : callback;
    var sql = "INSERT INTO t_rooms(uuid,id,base_info,ip,port,maxGames,costGems,create_time,seat_num) VALUES({0},{1},'{2}','{3}',{4},{5},{6},{7},{8})";

    var uuid = Date.now() + roomId;
    var baseInfo = JSON.stringify(conf);
    sql = sql.format(uuid, roomId, baseInfo, ip, port, maxGames, cost, create_time, seat_num);
    console.log(sql);
    query(sql, function (err, row, fields) {
        // console.log(err,row,fields);
        if (err) {
            callback(null);
            console.log("err: create_room fail error message == " + err);
        }
        else {
            callback(uuid);
        }
    });
};

exports.get_room_uuid = function (roomId, callback) {
    callback = callback == null ? nop : callback;
    var sql = 'SELECT uuid FROM t_rooms WHERE id = "' + roomId + '"';
    query(sql, function (err, rows, fields) {
        if (err) {
            callback(null);
            console.log("err: get_room_uuid fail error message == " + err);
        }
        else {
            callback(rows[0].uuid);
        }
    });
};

exports.update_seat_info = function (roomId, seatIndex, userId, icon, name, callback) {
    callback = callback == null ? nop : callback;
    var sql = 'UPDATE t_rooms SET user_id{0} = {1},user_icon{0} = "{2}",user_name{0} = "{3}" WHERE id = "{4}"'
    sql = sql.format(seatIndex, userId, icon, name, roomId);
    //console.log(sql);
    query(sql, function (err, row, fields) {
        if (err) {
            callback(false);
            console.log("err: update_seat_info fail error message == " + err);
        }
        else {
            callback(true);
        }
    });
}

exports.update_num_of_turns = function (roomId, numOfTurns, callback) {
    callback = callback == null ? nop : callback;
    var sql = 'UPDATE t_rooms SET num_of_turns = {0} WHERE id = "{1}"'
    sql = sql.format(numOfTurns, roomId);
    console.log(sql);
    try {
        query(sql, function (err, row, fields) {
            if (err) {
                callback(false);
                console.log("err: update_num_of_turns fail,error message == " + err);
            }
            else {
                callback(true);
            }
        });
    } catch (error) {
        callback(false);
        console.log("err: catch update_num_of_turns error message == " + error);
    }
};

exports.update_next_button = function (roomId, nextButton, callback) {
    callback = callback == null ? nop : callback;
    var sql = 'UPDATE t_rooms SET next_button = {0} WHERE id = "{1}"'
    try {
        sql = sql.format(nextButton, roomId);
        //console.log(sql);
        query(sql, function (err, row, fields) {
            if (err) {
                callback(false);
                console.log("err: update_next_button fail,error message == " + err);
            }
            else {
                callback(true);
            }
        });
    } catch (error) {
        callback(false);
        console.log("err: catch update_next_button error message == " + error);
    }
};

exports.get_eachround_data = function (roomId, callback) {
    callback = callback == null ? nop : callback;
    if (roomId == null) {
        callback(null);
        return;
    }
    var dataList = [];
    var sql = 'SELECT banker_index,end_time,history FROM t_each_round_history WHERE room_id = "' + roomId + '"';
    query(sql, function (err, rows, fields) {
        if (err) {
            callback(null);
            console.log("err: get_eachround_banker fail,error message == " + err);
            return;
        }
        if (rows.length <= 0) {
            callback(null);
            console.log("err: get_eachround_banker fail,error message == " + err);
            return;
        }
        else {
            for (var i = 0; i < rows.length; ++i) {
                dataList.push({
                    banker_index: rows[i].banker_index,
                    end_time: rows[i].end_time,
                    history: JSON.parse(rows[i].history),
                });
            }
            callback(dataList);
        }
    });
};


exports.get_shisanshui_eachround_data = function (roomId, callback) {
    callback = callback == null ? nop : callback;
    if (roomId == null) {
        callback(null);
        return;
    }
    var dataList = [];
    var sql = 'SELECT banker_mode,end_time,history FROM t_shisanshui_each_round_history WHERE room_id = "' + roomId + '"';
    query(sql, function (err, rows, fields) {
        if (err) {
            callback(null);
            console.log("err: get_shisanshui_eachround_data fail,error message == " + err);
            return;
        }
        if (rows.length <= 0) {
            callback(null);
            console.log("err: get_shisanshui_eachround_data fail,error message == " + err);
            return;
        }
        else {
            for (var i = 0; i < rows.length; ++i) {
                dataList.push({
                    banker_index: rows[i].banker_mode,
                    end_time: rows[i].end_time,
                    history: JSON.parse(rows[i].history),
                });
            }
            callback(dataList);
        }
    });
};

exports.get_activity_data = function (callback) {
    callback = callback == null ? nop : callback;
    var sql = "SELECT * FROM t_activity where is_show = 1 ORDER BY record_time DESC LIMIT 4";
    query(sql, function (err, rows, fields) {
        if (err) {
            callback(null);
            console.log("err: get_eachround_banker fail,error message == " + err);
            return;
        }
        if (rows.length <= 0) {
            callback(null);
            console.log("err: get_eachround_banker fail,error message == " + err);
            return;
        } else {
            callback(rows);
        }
    });
}

exports.get_all_eachround_data = function (callback) {
    callback = callback == null ? nop : callback;
    var dataList = [];
    var sql = 'SELECT room_id,round_no,history FROM t_each_round_history; ';
    query(sql, function (err, rows, fields) {
        if (err) {
            callback(null);
            console.log("err: get_eachround_banker fail,error message == " + err);
            return;
        }
        if (rows.length <= 0) {
            callback(null);
            console.log("err: get_eachround_banker fail,error message == " + err);
            return;
        }
        else {
            for (var i = 0; i < rows.length; ++i) {
                var historyData = JSON.parse(rows[i].history);
                dataList.push({
                    banker_index: rows[i].room_id,
                    end_time: rows[i].round_no,
                    history: historyData,
                });
                //console.log(dataList);
                var room_id = historyData.id;
                var round_no = rows[i].round_no;
                var users = '';
                var score = '';
                for (let j = 0; j < historyData.seats.length; ++j) {
                    let eachseat = historyData.seats[j];
                    //console.log(eachseat);
                    if (eachseat != null) {
                        if (users == '') {
                            if (eachseat.userid != null) {
                                users += eachseat.userid;
                                score += eachseat.score;
                            }
                        }
                        else {
                            if (eachseat.userid != null) {
                                users += (',' + eachseat.userid);
                                score += (',' + eachseat.score);
                            }
                        }
                    }
                }
                var sql2 = "insert into  t_each_round_users (room_id,round_no,users,scores) value ('{0}',{1},'{2}','{3}')";
                sql2 = sql2.format(room_id, round_no, users, score);
                query(sql2, function (err, rows, fields) {
                    if (err) {
                        callback(null);
                        console.log("err: get_all_eachround_data fail,error message == " + err);
                        return;
                    } else {
                        //console.log("get_all_eachround_data success");
                    }
                });
                console.log('res:   ', room_id, round_no, users, score);
            }
            //callback(dataList);
            //console.log(dataList);
        }
    });
};

exports.update_eachround_user_data = function (callback) {
    callback = callback == null ? nop : callback;
    var sql = 'SELECT room_id,round_no,history,userid1 FROM t_each_round_history; ';
    query(sql, function (err, rows, fields) {
        if (err) {
            callback(null);
            console.log("err: get_eachround_banker fail,error message == " + err);
            return;
        }
        if (rows.length <= 0) {
            callback(null);
            console.log("err: get_eachround_banker fail,error message == " + err);
            return;
        }
        else {
            //console.log("total column is ",rows.length);
            var total = rows.length;
            var i = 0;
            for (; i < total;) {
                var historyData = JSON.parse(rows[i].history);
                if (rows[i].userid1 > 0) {
                    ++i;
                    continue;
                } else {
                    break;
                }
            }
            var timer = setInterval(function (ret) {
                if (i >= total) {
                    clearInterval(timer);
                    console.log("clear timer");
                    return;
                }
                var historyData = JSON.parse(rows[i].history);
                var room_id = historyData.id;
                var round_no = rows[i].round_no;
                console.log("userid1 = ", rows[i].userid1)
                if (rows[i].userid1 == null) {
                    sql = "update t_each_round_history set  ";
                    for (let j = 0; j < historyData.seats.length; ++j) {
                        let eachseat = historyData.seats[j];
                        //console.log(eachseat);
                        if (eachseat != null) {
                            if (j == 0) {
                                sql += "userid1 = " + eachseat.userid;
                            } else {
                                sql += " , userid" + (j + 1) + " = " + eachseat.userid;
                            }
                        }
                    }
                    sql += " where room_id = " + room_id + " and round_no = '" + round_no + "'";
                    console.log(sql);
                    //var sql2 = "insert into  t_each_round_users (room_id,round_no,users,scores) value ('{0}',{1},'{2}','{3}')";
                    //sql2 = sql2.format(room_id, round_no, users, score);
                    query(sql, function (err, rows, fields) {
                        if (err) {
                            callback(null);
                            console.log("err: get_all_eachround_data fail,error message == " + err);
                            //return;
                        } else {
                            //console.log("get_all_eachround_data success");
                        }
                    });
                }
                ++i;
            }, 50);

            console.log("finish!");
        }
    });
};

exports.get_room_addr = function (roomId, callback) {
    callback = callback == null ? nop : callback;
    if (roomId == null) {
        callback(false, null, null);
        return;
    }

    var sql = 'SELECT ip,port FROM t_rooms WHERE id = "' + roomId + '"';
    query(sql, function (err, rows, fields) {
        if (err) {
            callback(false, null, null);
            console.log("err: get_room_addr fail,error message == " + err);
            return;
        }
        if (rows.length > 0) {
            callback(true, rows[0].ip, rows[0].port);
        }
        else {
            callback(false, null, null);
        }
    });
};

exports.get_room_data = function (roomId, callback) {
    callback = callback == null ? nop : callback;
    if (roomId == null) {
        callback(null);
        return;
    }

    var sql = 'SELECT * FROM t_rooms WHERE id = "' + roomId + '"';
    try {
        query(sql, function (err, rows, fields) {
            if (err) {
                callback(null);
                console.log("err: get_room_data fail error message == " + err);
                return;
            }
            if (rows.length > 0) {
                callback(rows[0]);
            }
            else {
                callback(null);
            }
        });
    } catch (error) {
        callback(null);
        console.log("err: catch get_room_data error message == " + error);
    }
};

exports.get_valid_room_info = function (callback) {
    callback = callback == null ? nop : callback;
    var sql = 'SELECT * FROM t_rooms';
    try {
        query(sql, function (err, rows, fields) {
            if (err) {
                callback(null, null);
                console.log("err: get_valid_room_info fail error message == " + err);
                return;
            }
            if (rows.length > 0) {
                var room_setting = {};
                var room_uuid = {};
                for (var i = 0; i < rows.length; ++i) {
                    var room_info = {
                        uuid: rows[i].uuid,
                        id: rows[i].id,
                        base_info: rows[i].base_info,
                        create_time: rows[i].create_time,
                        num_of_turns: rows[i].num_of_turns,
                        next_button: rows[i].next_button,
                        ip: rows[i].ip,
                        port: rows[i].port,
                        maxGames: rows[i].maxGames,
                        costGems: rows[i].costGems,
                    };
                    room_setting[room_info.id] = room_info;
                    room_uuid[room_info.uuid] = room_info.id;
                    callback(room_setting, room_uuid);
                }
            }
            else {
                callback(null, null);
            }
        });
    } catch (error) {
        callback(null, null);
        console.log("err: catch get_room_data error message == " + error);
    }
}

exports.delete_room = function (roomId, callback) {
    callback = callback == null ? nop : callback;
    if (roomId == null) {
        callback(false);
    }
    var sql = "DELETE FROM t_rooms WHERE id = '{0}'";
    sql = sql.format(roomId);
    console.log(sql);
    query(sql, function (err, rows, fields) {
        if (err) {
            callback(false);
            console.log("err: delete_room fail error message == " + err);
        }
        else {
            callback(true);
        }
    });
}

exports.create_game = function (room_uuid, index, base_info, callback) {
    callback = callback == null ? nop : callback;
    var sql = "INSERT INTO t_games(room_uuid,game_index,base_info,create_time) VALUES('{0}',{1},'{2}',unix_timestamp(now()))";
    sql = sql.format(room_uuid, index, base_info);
    try {
        query(sql, function (err, rows, fields) {
            if (err) {
                callback(null);
                console.log("err: create_game fail error message == " + err);
            }
            else {
                callback(rows.insertId);
            }
        });
    }
    catch (error) {
        callback(null);
        console.log("err: catch create_game error message == " + error);
    }
};

exports.store_game_round_result = function (room_uuid, index, base_info, actions, result, callback) {
    callback = callback == null ? nop : callback;
    var sql = "INSERT INTO t_games(room_uuid,game_index,base_info,create_time,action_records,result) VALUES('{0}',{1},'{2}',unix_timestamp(now()),'{3}','{4}')";
    sql = sql.format(room_uuid, index, base_info, actions, result);
    //console.log(sql);
    try {
        query(sql, function (err, rows, fields) {
            if (err) {
                callback(null);
                console.log("err: create_new_game fail! error message == " + err);
            }
            else {
                callback(rows.insertId);
            }
        });
    }
    catch (error) {
        callback(null);
        console.log("err: catch create_new_game error message == " + error);
    }
};







exports.create_order = function (orderInfo) {
    return new Promise(function (resolve, reject) {
        var sql = " INSERT INTO t_orders(userId, sdcustomno, type, gems, money, payment, state, createTime, updateTime) VALUE(" +
            orderInfo.userId + ",'" + orderInfo.sdcustomno + "'," + orderInfo.type + "," + orderInfo.gems + "," + orderInfo.money + ",'" + orderInfo.payment + "'," + orderInfo.state + ", now(), now())"
        console.log(sql)
        query(sql, function (err, rows, fields) {
            if (err) {
                console.log("err: t_orders fail error message == " + err);
                reject(false);
            }
            else {
                resolve(true);
            }
        });
    });
};

exports.update_order = function (sdcustomno, state, connQuery) {
    connQuery = connQuery ? connQuery : query;
    return new Promise(function (resolve, reject) {
        var sql = "UPDATE t_orders SET state = ?, updateTime = now() WHERE sdcustomno = ?";
        connQuery(sql, [state, sdcustomno])
            .then(function (rows) {
                resolve(true);
            }).catch(function (err) {
                console.log(err);
                reject(false);
            })
    });
};


exports.get_order_userId_bySdcustomno = function (sdcustomn, connQuery) {
    connQuery = connQuery ? connQuery : query;
    return new Promise(function (resolve, reject) {
        var sql = "SELECT userId FROM t_orders WHERE sdcustomno = ?";
        connQuery(sql, [sdcustomn])
            .then(function (rows) {
                if (rows.length > 0) {
                    resolve(rows[0].userId);
                } else {
                    reject(false);
                }
            }).catch(function (err) {
                console.log(err);
                reject(false);
            })
    });
};


exports.get_pay_config = function (connQuery) {
    connQuery = queryAsync();
    return new Promise(function (resolve, reject) {
        var sql = "SELECT * FROM t_pay_configs";
        connQuery(sql)
            .then(function (rows) {
                if (rows.length > 0) {
                    resolve(rows);
                } else {
                    reject([]);
                }
            }).catch(function (err) {
                console.log(err);
                reject(err);
            })
    });
};





exports.update_user_gems = function (userId, gem, type, connQuery) {
    connQuery = connQuery ? connQuery : query;
    return new Promise(function (resolve, reject) {
        if (!gem) {
            reject(false);
        }
        var sql = "UPDATE t_users SET gems = gems + ? WHERE userId = ?";
        if (type == 1) {
            sql = "UPDATE t_users SET coins = coins + ? WHERE userId = ?";
        }
        connQuery(sql, [gem, userId])
            .then(function (rows) {
                resolve(true);
            }).catch(function (err) {
                console.log(err);
                reject(false);
            })
    });
};


exports.get_user_gems = function (userId, type, connQuery) {
    connQuery = connQuery ? connQuery : query;
    return new Promise(function (resolve, reject) {
        var sql = "SELECT gems FROM t_users WHERE userId = {0}";
        sql = sql.format(userId);
        if (type == 1) {
            sql = "SELECT coins FROM t_users WHERE userId = {0}";
            sql = sql.format(userId);
        }
        connQuery(sql, function (err, rows) {
            if (err) {
                console.log("search t_users gems error" + err);
                return reject(false);
            }

            if (rows.length > 0) {
                console.log("search t_users gems sucess");
                resolve(rows[0].gems);
            } else {
                reject(false);
            }
        })
    });
};



exports.get_orderstatus_by_sdcustomno = function (sdcustomno) {
    return new Promise(function (resolve, reject) {
        var sql = "SELECT state, type FROM t_orders WHERE sdcustomno = '{0}'";
        sql = sql.format(sdcustomno);
        query(sql, function (err, rows, fields) {
            if (err) {
                console.log("err: t_orders fail error message == " + err);
                reject(false);
            }
            else {
                if (rows.length) {
                    resolve(rows[0]);
                } else {
                    console.log("err: t_orders fail error message not find sdcustomno ");
                    reject(false);
                }
            }
        });
    });
};



exports.delete_games = function (room_uuid, callback) {
    callback = callback == null ? nop : callback;
    if (room_uuid == null) {
        callback(false);
    }
    var sql = "DELETE FROM t_games WHERE room_uuid = '{0}'";
    sql = sql.format(room_uuid);
    try {
        query(sql, function (err, rows, fields) {
            if (err) {
                callback(false);
                console.log("err: delete_games fail error message == " + err);
            }
            else {
                callback(true);
            }
        });
    }
    catch (error) {
        callback(false);
        console.log("err: catch delete_games error message == " + error);
    }
}

exports.archive_games = function (room_uuid, callback) {
    callback = callback == null ? nop : callback;
    if (room_uuid == null) {
        callback(false);
    }
    var sql = "INSERT INTO t_games_archive(SELECT * FROM t_games WHERE room_uuid = '{0}')";
    sql = sql.format(room_uuid);
    //console.log(sql);
    query(sql, function (err, rows, fields) {
        if (err) {
            callback(false);
            console.log("err: archive_games fail error message == " + err);
        }
        else {
            exports.delete_games(room_uuid, function (ret) {
                callback(ret);
            });
        }
    });
}

exports.update_game_action_records = function (room_uuid, index, actions, callback) {
    callback = callback == null ? nop : callback;
    var sql = "UPDATE t_games SET action_records = '" + actions + "' WHERE room_uuid = '" + room_uuid + "' AND game_index = " + index;

    try {
        query(sql, function (err, rows, fields) {
            if (err) {
                callback(false);
                console.log("err: update_game_action_records fail! error message == " + err);
            }
            else {
                callback(true);
            }
        });
    } catch (error) {
        callback(false);
        console.log("err: catch update_game_action_records error message == " + error);
    }

};

exports.update_game_result = function (room_uuid, index, result, callback) {
    callback = callback == null ? nop : callback;
    if (room_uuid == null || result) {
        callback(false);
    }

    result = JSON.stringify(result);
    var sql = "UPDATE t_games SET result = '" + result + "' WHERE room_uuid = '" + room_uuid + "' AND game_index = " + index;
    try {
        query(sql, function (err, rows, fields) {
            if (err) {
                callback(false);
                console.log("err: update_game_result fail error message == " + err);
            }
            else {
                callback(true);
            }
        });
    } catch (error) {
        callback(false);
        console.log("err: catch update_game_result error message == " + error);
    }
};

exports.get_message = function (type, version, callback) {
    callback = callback == null ? nop : callback;

    var sql = 'SELECT * FROM t_message WHERE type = "' + type + '"';

    if (version == "null") {
        version = null;
    }

    if (version) {
        version = '"' + version + '"';
        sql += ' AND version != ' + version;
    }

    query(sql, function (err, rows, fields) {
        if (err) {
            callback(false);
            console.log("err: get_message fail error message == " + err);
        }
        else {
            if (rows.length > 0) {
                callback(rows[0]);
            }
            else {
                callback(null);
            }
        }
    });
};

exports.recordLoginLog = function (userid, callback) {
    callback = callback == null ? nop : callback;

    var sql = 'insert into t_login_log (userid) values (' + userid + ')';
    query(sql, function (err, rows, fields) {
        if (err) {
            callback(false);
            console.log("err: recordLogin fail error message == " + err);
        }
        else {
            callback(true);
        }
    });
}

exports.updateOnlineStatus = function (userid, status, callback) {
    callback = callback == null ? nop : callback;
    var sql = 'update t_users set online = ' + status + ' where userid = ' + userid;
    query(sql, function (err, rows, fields) {
        if (err) {
            callback(false);
            console.log("err: updateOnlineStatus fail error message == " + err);
        }
        else {
            callback(true);
        }
    });
}

exports.updateUserSharedGiveDiamonds = function (userid, number, callback) {
    callback === undefined ? nop : callback;
    var date = moment().format("YYYY-MM-DD");
    var sql =
        "SELECT  count(*) as count" +
        " FROM t_diamond_record" +
        " WHERE userid =" + userid + " AND DATE(record_time) ='" + date + "'";
    query(sql, function (err, rows, fields) {
        if (err) {
            callback(false);
            console.log("err: updateUserSharedGiveDiamonds fail error message == " + err);
        } else {
            console.log(rows);
            if (rows && rows[0].count > 0) {
                return callback(false);
            }
            sql =
                "INSERT INTO t_diamond_record" +
                " VALUES(" + userid + ", now()," + number + ", 1)";
            query(sql, function (err, rows, fields) {
                if (err) {
                    callback(false);
                    console.log("err: updateUserSharedGiveDiamonds fail error message == " + err);
                } else {
                    //   更新钻石数
                    exports.cost_gems(userid, -number, function () {
                        callback(true);
                    });
                }
            });
        }
    });
}

exports.isCanMoAnyPai = function (userId, callback) {
    callback === undefined ? nop : callback;
    var sql = "select isMoAnyPai from t_users where userid = " + userId;
    query(sql, function (err, rows, fields) {
        if (err) {
            callback(null);
            console.log("err: isCanMoAnyPai fail error message == " + err);
        } else {
            if (rows && rows.length > 0) {
                return callback(rows[0]);
            }
        }
    });
}

exports.getGameInfo = function (callback) {
    callback === undefined ? nop : callback;
    var sql = "select * from t_game_list";
    console.log(sql);
    query(sql, function (err, rows, fields) {
        if (err) {
            callback(null);
            console.log("err: getGameInfo fail error message == " + err);
        } else {
            if (rows && rows.length > 0) {
                return callback(rows[0]);
            }
        }
    });
}

exports.query = query;

//var date = new Date("2017-07-20 20:16:00");
exports.generate_eachround_history = function (roomInfo, seatNum, callback) {
    //庄家
    callback = callback == null ? nop : callback;
    var seats = roomInfo.seats;
    var history = {
        uuid: roomInfo.uuid,
        id: roomInfo.id,
        time: roomInfo.createTime,
        seats: new Array(seatNum)
    };
    for (var i = 0; i < seats.length; ++i) {
        var rs = seats[i];
        var hs = history.seats[i] = {};
        hs.userid = rs.userid;
        hs.name = rs.name;
        hs.score = rs.score;
    }

    //console.log("num == ", roomInfo.numOfGames);
    if (roomInfo.begin_time_tmp == 0) {
        roomInfo.begin_time_tmp = Date.now() - 100000;
    } else {
        var randNum = 6000 + Math.floor(Math.random() * 4000);
        //console.log("rand num = ", randNum);
        roomInfo.begin_time_tmp = (roomInfo.end_time_tmp + randNum);
        //console.log("begin val = ", begin_time_tmp);
    }

    var begin_time = moment(roomInfo.begin_time_tmp).format("YYYY-MM-DD HH:mm:ss");
    //console.log("begin time . = ", begin_time);
    roomInfo.end_time_tmp = roomInfo.begin_time_tmp + 50000 + Math.floor(Math.random() * 50000);
    var end_time = moment(roomInfo.end_time_tmp).format("YYYY-MM-DD HH:mm:ss");
    //console.log('end time . = ', end_time);

    //构造语句
    history = JSON.stringify(history);
    var sql = "insert into t_each_round_history (room_uuid,room_id,banker_index,history,round_no,begin_time,end_time,userid1,userid2) values ('{0}','{1}',{2},'{3}',{4},'{5}','{6}','{7}','{8}')";
    sql = sql.format(roomInfo.uuid, roomInfo.id, roomInfo.nextButton, history, roomInfo.numOfGames, begin_time, end_time, seats[0].userid, seats[1].userid);
    console.log(sql);
    query(sql, function (err, rows, fields) {
        if (err) {
            //callback(false);
            console.log("err: insert into t_each_round_history fail error message == " + err);
        }
        else {
            //callback(true);
            console.log("insert into t_each_round_history success");
        }
    });
    var historyData = JSON.parse(history);
    //console.log(dataList);
    var room_id = historyData.id;
    var round_no = roomInfo.numOfGames;
    var users = '';
    var score = '';
    for (let j = 0; j < roomInfo.seats.length; ++j) {
        let eachseat = roomInfo.seats[j];
        if (eachseat != null) {
            if (users == '') {
                if (eachseat.userid != null) {
                    users += eachseat.userid;
                    score += eachseat.score;
                }
            }
            else {
                if (eachseat.userid != null) {
                    users += (',' + eachseat.userid);
                    score += (',' + eachseat.score);
                }
            }
        }
    }
    var sql2 = "insert into  t_each_round_users (room_id,round_no,users,scores) value ('{0}',{1},'{2}','{3}')";
    sql2 = sql2.format(room_id, round_no, users, score);
    console.log(sql2);
    query(sql2, function (err, rows, fields) {
        if (err) {
            callback(false);
            console.log("err: insert into t_each_round_users fail,error message == " + err);
            return;
        } else {
            console.log("insert into t_each_round_users success");
            callback(true);
        }
    });
    //console.log('res:   ', room_id, round_no, users, score);
}

exports.generate_user = function (userid, account, name, level, coins, gems, sex, headimg, callback) {
    callback = callback == null ? nop : callback;
    if (account == null || name == null || coins == null || gems == null) {
        callback(0, false);
        return;
    }
    if (headimg == null) {
        headimg = 'null';
    }
    var sql = 'INSERT INTO t_users(userid,account,name,lv,coins,gems,sex,headimg) VALUES ({0},"{1}","{2}",{3},{4},{5},{6},"{7}")';
    sql = sql.format(userid, account, name, level, coins, gems, sex, headimg);
    console.log(sql);
    query(sql, function (err, rows, fields) {
        if (err) {
            callback(0, false);
            console.log("err: create_user fail error message == " + err);
            return;
        }
        callback(userid, true);
    });
};

exports.is_name_exist = function (name, callback) {
    callback = callback == null ? nop : callback;
    if (name == null) {
        callback(0, false);
        return;
    }

    var sql = 'select count(*) as count from t_users where name like "' + name + '"';
    //sql = sql.format(name);
    console.log(sql);
    query(sql, function (err, rows, fields) {
        if (err) {
            callback(0, false);
            console.log("err: create_user fail error message == " + err);
            return;
        }
        if (rows.length > 0) {
            callback(rows[0].count, true);
        }
    });
}

exports.isCreator = function (userId, roomId, callback) {
    callback = callback == null ? nop : callback;
    if (roomId == null || userId == null) {
        callback(0, false);
        return;
    }
    var sql = 'select count(*) as count from t_rooms where base_info like "%{0}%" and id = "{1}"';
    sql = sql.format(userId, roomId);
    //console.log(sql);
    query(sql, function (err, rows, fields) {
        if (err) {
            callback(0, false);
            console.log("err: isCreator fail error message == " + err);
            return;
        }
        if (rows.length > 0) {
            callback(rows[0].count, true);
        } else {
            callback(0, false);
        }
    });
}

exports.getRoomCostConfig = function (seatLen, roundNO, callback){
    callback = callback == null ? nop : callback;
    if (seatLen == null || roundNO == null) {
        callback(0, false);
        return;
    }
    var sql = 'select * from t_room_cost_config where room_type = {0} and round_no = {1} ';
    sql = sql.format(seatLen, roundNO);
    console.log(sql);
    query(sql, function (err, rows, fields) {
        if (err) {
            callback(0, false);
            console.log("err: isCreator fail error message == " + err);
            return;
        }
        if (rows.length > 0) {
            callback(rows[0].cost_diamond, true);
        } else {
            callback(0, false);
        }
    });
}

exports.getAllCostConfig = function (callback){
    callback = callback == null ? nop : callback;
    var sql = 'select * from t_room_cost_config ';
    console.log(sql);
    query(sql, function (err, rows, fields) {
        if (err) {
            callback(0, false);
            console.log("err: isCreator fail error message == " + err);
            return;
        }
        if (rows.length > 0) {
            callback(rows, true);
        } else {
            callback(0, false);
        }
    });
}